const chatMessages = document.getElementById('chat-messages');
const userInput = document.getElementById('user-input');
const sendButton = document.getElementById('send-button');

function addMessage(sender, content, isUser = false) {
    const messageDiv = document.createElement('div');
    messageDiv.classList.add('message');
    if (isUser) {
        messageDiv.classList.add('user-message');
    } else {
        messageDiv.classList.add('ai-message');
    }

    const senderDiv = document.createElement('div');
    senderDiv.classList.add('message-sender');
    senderDiv.textContent = sender;

    const contentDiv = document.createElement('div');
    contentDiv.classList.add('message-content');

    contentDiv.innerHTML = formatMessageContent(content);


    messageDiv.appendChild(senderDiv);
    messageDiv.appendChild(contentDiv);
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function formatMessageContent(text) {
    text = text.replace(/\n/g, '<br>');

    text = text.replace(/```([\s\S]*?)```/g, (match, code) => {
        const escapedCode = escapeHtml(code);
        return `<pre>${escapedCode}</pre>`;
    });

      text = text.replace(/`([^`]+)`/g, (match, inlineCode) => {
        const escapedInlineCode = escapeHtml(inlineCode);
        return `<code>${escapedInlineCode}</code>`;
    });

    return text;
}

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
}



async function sendMessage() {
    const message = userInput.value.trim();
    if (!message) return;

    addMessage('你', message, true);
    userInput.value = '';

     const aiResponseDiv = document.createElement('div');
     aiResponseDiv.classList.add('message', 'ai-message');
     aiResponseDiv.innerHTML = `<strong>AI:</strong> <span></span>`;
     chatMessages.appendChild(aiResponseDiv);
     const aiSpan = aiResponseDiv.querySelector('span');


    try {
        const response = await fetch('chat.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ message: message }),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');

        while (true) {
            const { done, value } = await reader.read();
            if (done) {
                break;
            }

            const chunk = decoder.decode(value); 
            const lines = chunk.split('\n').filter(line => line.trim() !== '');
            for (const line of lines) {
                if (line.startsWith('data:')) {
                    const jsonData = line.substring(5).trim();

                     if (jsonData === '[DONE]') {
                         break;
                     }

                    try {
                        const parsedData = JSON.parse(jsonData);
                        const content = parsedData.choices[0].delta.content;
                        if(content){
                            aiSpan.textContent += content;
                            chatMessages.scrollTop = chatMessages.scrollHeight;
                        }

                    } catch (error) {
                        console.error('JSON parsing error:', error);
                    }
                }
            }
        }


    } catch (error) {
        console.error('Fetch error:', error);
        addMessage('AI', '抱歉，出错了。');
    }
}

sendButton.addEventListener('click', sendMessage);
userInput.addEventListener('keydown', (event) => {
    if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
    }
});
